package com.buka.controller;

import com.buka.entity.Result;
import com.buka.entity.StatusCode;
import com.buka.pay.AliPay;
import com.buka.pojo.Order;
import com.buka.service.AliPayService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;


import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

import java.util.Map;

/**
 * 支付宝支付
 */
@RestController
@RequestMapping("/alipay")
@Transactional(rollbackFor = Exception.class)
public class AliPayController {
    private static final String CHARSET = "utf-8";

    @Autowired
    private AliPayService aliPayService;

    /**
     * h5支付
     *
     * @param aliPay
     * @param httpResponse
     * @throws Exception
     */
    @GetMapping("/pay")
    public void pay(AliPay aliPay, HttpServletResponse httpResponse) throws Exception {
        String form = aliPayService.H5Pay(aliPay);
        httpResponse.setContentType("text/html;charset=" + CHARSET);
        // 直接将完整的表单html输出到页面
        httpResponse.getWriter().write(form);
        httpResponse.getWriter().flush();
        httpResponse.getWriter().close();
    }

    /**
     * 退款
     * @param aliPay
     * @return
     */
    @RequestMapping("/refund")
    public Result refund(AliPay aliPay) {
        return new Result(aliPayService.refund(aliPay));
    }

    /**
     * 查看支付订单信息
     */
    @RequestMapping("/query")
    public Map queryPayment(AliPay aliPay) {
        return aliPayService.query(aliPay);
    }


    @RequestMapping("/OrderPay")
    public Result OrderPay(@RequestParam String orderId, HttpServletResponse httpResponse) throws IOException {
        String form;
        try{
             form= aliPayService.OrderPay(orderId);
        }catch (Exception e){
            return new Result(false, StatusCode.ERROR,"支付失败");
        }
        httpResponse.setContentType("text/html;charset=" + CHARSET);
        // 直接将完整的表单html输出到页面
        httpResponse.getWriter().write(form);
        httpResponse.getWriter().flush();
        httpResponse.getWriter().close();
        return new Result(true,StatusCode.OK,"成功");
    }
}